import { addCart, findCart, deleteCart, checkCartGoods, clearCart } from '@/api/goods'
// 购物车状态
export default {
  namespaced: true,
  state: () => {
    return {
      buy: {}, // 立即购买
      list: []
    }
  },
  // 修改购物车函数
  mutations: {
    addBuy (state, goods) {
      console.log(goods)
      state.buy = goods
    },
    // 覆盖购物车数据
    setCartList (state, list) {
      state.list = list
    },
    // 清空购物车
    deletaAllCart (state) {
      state.list = []
    },
    // 删除购物车商品
    deleteCart (state, skuId) {
      const index = state.list.findIndex(item => item.skuId === skuId)
      state.list.splice(index, 1)
    },
    // 加入购物车
    insertCart (state, payload) {
      // 考虑两种情况：
      const index = state.list.findIndex(item => item.skuId === payload.skuId)
      //  情况1：没有添加过的就添加到列表前
      if (index === -1) {
        state.list.unshift(payload)
      } else {
        //  情况2：已经添加过的商品(skuid已存在)，是数量的累加
        state.list[index].count += payload.count
      }
    },
    // 全选和反全选
    addCheck (state, payload) {
      state.list.forEach(goods => {
        goods.selected = payload
      })
    }
  },
  // 异步操作购物车的函数
  actions: {
    // 清空购物车
    delAllCart (store) {
      return new Promise((resolve) => {
        clearCart().then(() => {
          store.dispatch('findCartList')
          resolve('清空购物车操作')
        })
      })
    },
    // 做有效商品的全选&反选
    checkAllCart (store, selected) {
      store.commit('addCheck', selected)
    },
    // 更新购物车商品 数量
    updateCart (store, goods) {
      return new Promise((resolve) => {
        addCart({ goods_id: goods.id, sku_id: goods.sku_id, c_num: goods.buy_num }).then(() => {
          store.dispatch('findCartList')
        })
        resolve('线上接口')
      })
    },
    // 根据id删除购物车商品
    deleteCart (store, skuId) {
      return new Promise((resolve) => {
        deleteCart(skuId).then(() => {
          store.dispatch('findCartList')
        })
        resolve('线上接口')
      })
    },
    // 获取购物车列表
    findCartList (store) {
      return new Promise((resolve) => {
        // 情况1：有登录
        if (store.rootState.user.profile.token) {
          // 登录后 TODO ...
          // resolve('线上接口')
          findCart().then((res) => {
            const list = res.data.mch_goods_list.length > 0 ? res.data.mch_goods_list[0].goods_list : []
            list.forEach(item => {
              if (item.sku_price.length > 0) {
                // 获取sku价格存入，
                const skuObj = item.sku_price.find(v => v.id === item.sku_id)
                // item.imputed_price = item.sku_price[item.sku_price.findIndex(v => v.id === item.sku_id)].price
                item.imputed_price = skuObj.price
                item.imputed_sku = skuObj.name
                item.imputed_stock = +skuObj.stock
              } else {
                item.imputed_price = item.price
                item.imputed_sku = ''
                item.imputed_stock = +item.stock
              }
            })
            store.commit('setCartList', list)
            resolve('获取购物车成功-线上')
          })
        } else {
          resolve('获取购物车成功-本地')
        }
      })
    },
    // 加入购物车
    insertCart (store, payload) {
      return new Promise((resolve) => {
        addCart({ goods_id: payload.id, sku_id: payload.skuId, num: payload.count }).then(() => {
          store.dispatch('findCartList') // 获取购物车列表
          resolve('加入购物车成功')
        })
      })
    },
    // 购物车商品选中和未选中状态
    updateCheck (store, payload) {
      return new Promise((resolve) => {
        // console.log(payload.cart_id)
        checkCartGoods(payload.is_checked, payload.cart_id).then(() => {
          // store.dispatch('findCartList') // 获取购物车列表
          resolve('更新购物车选中状态')
        })
          .catch(() => {
            store.dispatch('findCartList')
          })
      })
    }
  },
  // 相当于计算属性
  getters: {
    // 选中商品列表
    selectedList (state, getters) {
      return getters.validList.filter(item => item.is_checked === 1)
    },
    // 选中商品件数
    selectedTotal (state, getters) {
      // return getters.selectedList.reduce((p, c) => p + c.count, 0)
      return getters.selectedList.reduce((p, c) => p + c.buy_num, 0)
    },
    // 选中商品总金额
    selectedAmount (state, getters) {
      return getters.selectedList.reduce((p, c) => {
        return (p += (+c.imputed_price * +c.buy_num))
      }, 0)
    },
    // 选中商品运费
    selectedFreight (state, getters) {
      return getters.selectedList.reduce((p, c) => p + +c.freight_money, 0)
    },
    // 有效商品列表
    // validList (state) {
    //   return state.list.filter(item => item.stock > 0 && item.isEffective)
    // },
    validList (state) {
      return state.list
    },
    // 是否全选
    isCheckAll (state, getters) {
      return getters.selectedList.length !== 0 && getters.validList.length === getters.selectedList.length
    },
    // 有效商品件数
    validTotal (state, getters) {
      return getters.validList.reduce((total, item) => item.buy_num + total, 0)
    },
    // 有效商品总金额
    validAmount (state, getters) {
      return getters.validList.reduce((total, item) => item.nowPrice * 100 * item.count + total, 0) / 100
    },

    addGoods (state) {
      return state.buy
    }
  }
}
